package com.leaf.lowcode.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.leaf.lowcode.API.VistorEventApi;
import com.leaf.lowcode.entity.RecordsRequest;
import com.leaf.lowcode.mapper.ApptionmentMapper;
import com.leaf.lowcode.mapper.HkVisitorMapper;
import com.leaf.lowcode.utils.RegularInstance;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 访客到访与访客预约
 *到访，预约和预约率
 *
 */
@Component
public class DoorVistorCount {

    @Autowired
    private HkVisitorMapper hkVisitorMapper;
    @Autowired
    private ApptionmentMapper apptionmentMapper;

   @Scheduled(initialDelay = 1000, fixedRate = 1 * 1000)
    void execute() {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DAY_OF_MONTH, 0);
        //一天的开始时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date dayStart = calendar.getTime();
        String pattern = "YYYY-MM-dd'T'HH:mm:ssZZ";
        String startStr = DateFormatUtils.format(dayStart, pattern);
        System.out.println("startStr" + startStr);
        //一天的结束时间 yyyy:MM:dd 00:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date dayEnd = calendar.getTime();
        String endStr = DateFormatUtils.format(dayEnd, pattern);
        System.out.println("startStr" + endStr);

        //   String  orgName;
        System.out.println("访客事件启动");
        VistorEventApi vistorEventApi = new VistorEventApi();
        RecordsRequest searchesRequest = new RecordsRequest();
        searchesRequest.setPageNo(1);
        searchesRequest.setPageSize(1000);
        searchesRequest.setVisitEndTimeBegin(startStr);
        searchesRequest.setVisitEndTimeEnd(endStr);
        /**
         *
         */
        String StringtoJson = vistorEventApi.eventSearch(searchesRequest);
        JSONObject vistorJson = JSON.parseObject(StringtoJson);
        System.out.println(vistorJson);
        JSONArray vistorList = (JSONArray) ((JSONObject) vistorJson.get("data")).get("list");
        //今日来访客预约数量
        System.out.println("访客来访人数" + vistorList.size());

        String appointment = vistorEventApi.appointmentSearch(searchesRequest);
        JSONObject appointmentJson = JSON.parseObject(appointment);
        System.out.println(appointmentJson);
        JSONArray appointmentList = (JSONArray) ((JSONObject) appointmentJson.get("data")).get("list");
        //访客预约人数
        System.out.println("访客预约总数" + appointmentList.size());

        /**
         * 到访率
         */
        double vistorInRate = (vistorList.size() / appointmentList.size()) * 100;
        List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
        if (subDeviceDTOList != null) {
            for (SubDeviceDTO dto : subDeviceDTOList) {
                String pid = dto.getPid();
                String sn = dto.getSn();
                String din = dto.getDin();
                if (sn.equals("dyyfkgdtsn")) {
                    //  System.out.println("======================门禁卡========================"+readerdoorstatesend.getIndexCode());
                    System.out.println("getDin"+dto.getDin());
                    JSONObject standardData = new JSONObject();
                    standardData.put("reportTs", System.currentTimeMillis());
                    JSONObject profile = new JSONObject();
                    profile.put("modelId", 200725);
                    profile.put("poiCode", "w0717006");
                    profile.put("appType", "visitor");
                    standardData.put("profile", profile);
                    WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                    JSONObject events = new JSONObject();
                    JSONObject event = new JSONObject();
                    event.put("eventType", 1);
                    event.put("eventTs", System.currentTimeMillis());
                    event.put("describe", "");
                   /* event.put("visitcount",vistorList.size());
                    event.put("appointment", appointmentList.size());
                    event.put("rate", vistorInRate);
                    int cance=appointmentList.size()-vistorList.size();
                      event.put("cance",cance);
                   */
//模拟数据
                    event.put("visitcount",110);
                    event.put("appointment", 120);
                    event.put("rate", 0.4);
                    int cance=120-110;
                    event.put("cance",cance);
                    events.put("visit_rate", event);
                    standardData.put("events", events);
                    standardData.put("properties", new JSONObject());
                    //standardData.put("properties", "{}");
                    try {
                        System.out.println("上传数据");
                        String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                        System.out.println("发送设备运行时事件数据==" + devRunEvent);
                        System.out.println("--------------------------------开始传输设备运行时事件数据");
                        wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(din), devRunEvent, true);
                        System.out.println("ddddddd" + devRunEvent + "ssssss");
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("设备运行时事件数据传输出现异常");
                    }
                }
            }
        }
    }
}
